// components/comment/comment.js
const app = getApp()
const db = wx.cloud.database()
const {
  login,
  formatTime
} = require('../../utils/util')
const _ = db.command

//留言一共需要维护四个部分，分为页面本次创建部分，comment集合，commentBack集合，message部分
//本次创建部分也即新增留言和回复会直接setData已经存在的数据而不是重新从数据库拿，comment集合是持久化数据，里面的点赞留言回复都是有的，某种意义上只有这个集合就够了，而commentBack集合主要是通知用的，其实原本打算comment集合里的点赞和回复去commentBack遍历拿到，但是好麻烦，懒得写，这样也就意味着你要删除一个回复或点赞的话，你需要先到comment集合里找到goodNum和goodnum改变它，comment字段，再从对应到的commentBack集合去删除对应数据，才完全删除了，message集合纯粹为了小红点提示
Component({

  properties: {
    //主要是信息那里跳转时需要具体的under路径，这个是文件名而不是数据库集合名，比如eventDetails这个文件名就会跳
    undercollection: String,
    // 进入那个页面后onLoad会拿到这个id去数据库拿数据，跟分享页面点击打开的逻辑一样
    underid: String,
    //主要是消息那里会提示是在什么板块，所以就这个作用
    underTitle: String
  },

  data: {
    // 获取表情
    emojis: ["😀", "😁", "😂", "😃", "😄", "😅", "😆", "😉", "😊", "😋", "😎", "😍", "😘", "😗", "😙", "😚", "😇", "😐", "😑", "😶", "😏", "😣", "😥", "😮", "😯", "😪", "😫", "😴", "😌", "😛", "😜", "😝", "😒", "😓", "😔", "😕", "😲", "😷", "😖", "😞", "😟", "😤", "😢", "😭", "😦", "😧", "😨", "😬", '😰', '😱', '😳', '😵', '😡', '😠', '💘', '❤', '💓', '💔', '💕', '💖', '💗', '💙', '💚', '💛', '💜', '💝', '💞', '💟', '❣', '💪', '👈', '👉', '☝', '👆', '👇', '✌', '✋', '👌', '👍', '👎', '✊', "👊", "👋", "👏"],
    //留言是否显现，是否聚焦
    writeBol: false,
    //回复是否显现，是否聚焦
    writeBack: false,
    //回复框写的是什么
    backValue: "",
    //留言框写的是什么
    commentValue: "",
    //本人的照片
    avatarUrl: "",
    //本人昵称
    name: "",
    //所有留言及其回复
    comment: [],
    //点击回复后显示在回复框里回复谁的name
    commentBackName: "",
    //主要是写字框高度
    keybordHeight: 0,
    emoji: false,
    loading:true
  },


  ready() {
    //分页拿取评论数据
    this._pageIndex = 0
    //拿一下这个人的唯一标识
    this._openid = app.globalData.openid
    //第一次拿10条评论
    this.onReachBottom()

    // 监视键盘高度，对应设置回复框留言框位置
    wx.onKeyboardHeightChange(res => {
      if (res.height > this.data.keybordHeight) {
        this.setData({
          keybordHeight: res.height
        })
      }
    })
  },
  methods: {
    //到底部时分页拿数据
    onReachBottom() {
      this.setData({
        loading:true
      })
      db.collection("comments").where({
        underid: this.data.underid,
        underCollection: this.data.undercollection
        // 按点赞数排序
      }).orderBy('goodnum', 'desc').skip(this._pageIndex * 10).limit(10).get({
        success: (res) => {
          if (res.data.length <10) {
            this.setData({
              loading:false
            })
          }
          res.data.map(item => {
            item.likeed = false
            item.goodNum.map(i => {
              if (i.openid === this._openid) {
                item.likeed = true
              }
            })
          })
          this.setData({
            comment: this.data.comment.concat(res.data)
          })
          this._pageIndex++
        }
      })
    },
    // 主要是安卓没法即时响应所以弄的，留言填字按钮亮
    setCommentValue(e) {
      this.setData({
        commentValue: e.detail.value
      })
    },
    //为的是输入完emojy再点击后还可以退出
    setFocus(e) {
      this.setData({
        emoji: false
      })
    },
    //同上
    setBackValue(e) {

      this.setData({
        backValue: e.detail.value
      })

    },
    //点击留言后
    writeNow(e) {
      this.setData({
        textCursor: e.detail.cursor,
      })
      if (this.data.emoji === false) {
        //失去焦点时会false很明显
        this.setData({
          writeBol: !this.data.writeBol,
          commentValue: ""
        })
        this.animate(".writeComment", [{
          opacity: 0
        }, {
          opacity: 1
        }], 500)
      }
    },
    textInsertEmoji: function (e) {
      // 延时只是为了让textarea先失去焦点，以便获取光标位置
      setTimeout(() => {
        let icon = e.currentTarget.dataset.icon;
        let textCursor = this.data.textCursor;
        let commentValue =this.data.commentValue;
        let backValue =this.data.backValue;
        commentValue = commentValue.slice(0, textCursor) + icon + commentValue.slice(textCursor);
        backValue = backValue.slice(0, textCursor) + icon + backValue.slice(textCursor);
        this.setData({
          commentValue: commentValue,
          backValue:backValue,
          textCursor: textCursor + 4,
        })

      }, 100)
    },
    emoji() {
      this.setData({
        emoji: true
      })
    },
    //点击回复后记录回复的是谁以及在哪个留言下的交流
    callBack(e) {
      //是回复留言主还是留言下面的相互交流，1是回复留言主，2是留言下面的交流，3是点赞当然3不在这里出现
      this._callBackState = e.currentTarget.dataset.state
      //哪条留言下面
      this._index = e.currentTarget.dataset.index
      //更新的是哪条留言的id
      this._backid = e.currentTarget.dataset.updateid
      //回复的那个人的id
      this._backOpenId = e.currentTarget.dataset.item._openid
      //回复的那个人的头像
      this._backimgPhoto = e.currentTarget.dataset.item.imgPhoto
      //回复的那个人的名字，回复填写框要同时渲染
      this.setData({
        commentBackName: e.currentTarget.dataset.item.nickName
      })
      //让回复留言框显现
      this.setData({
        writeBack: true,
        backValue:""
      })
      //渐入动画
      this.animate(".release", [{
        opacity: 0
      }, {
        opacity: 1
      }], 500)
    },
    //回复框焦点消失
    hideKeyboard(e) {
      this.setData({
        textCursor: e.detail.cursor,
      })
      if (this.data.emoji === false) {
        this.setData({
          writeBack: false,
          backValue: ""
        })
      }
    },
    //有点赞和回复行为时会把消息推送到这个集合的那个接受体的message为true小红点亮起，特别注意update集合集合的_openid是更新者的id，所以我特别设置了一个openid集合
    addmessage(openid) {
      db.collection("message").where({
        openid: openid
      }).get({
        success: (res) => {
          //没有这个用户的文档则新建，有则update
          if (res.data.length === 0) {
            db.collection("message").add({
              data: {
                openid: openid,
                message: true
              }
            })
          } else {
            db.collection("message").where({
              openid: openid
            }).update({
              data: {
                openid: openid,
                message: true
              }
            })
          }
        }
      })
    },
    //点赞和取消点赞
    likeOrNo(e) {
      const item = e.currentTarget.dataset.item
      const index = e.currentTarget.dataset.index
      let time = formatTime(new Date())
      //每个留言的goodNum字段里存的是谁点赞了，刚拿到数据时看看这个字段里有没有这个用户，有则这个留言在这个用户的界面里likeed为true
      //点赞了再点就是取消点赞，没点就新增
      if (item.likeed) {
        //因为不会刷新，当点取消赞时可能另一边已经取消点赞而这里会保留另一边的点赞，并Update整个上去，所以再拿一次
        db.collection("comments").where({
          _id: item._id
        }).get({
          success: (res) => {
            res.data[0].goodNum.some((it, i) => {
              if (it.openid === this._openid) {
                res.data[0].goodNum.splice(i, 1)
                db.collection("commentBack").doc(it.connectid).remove({
                  success: function (res) {
                    console.log(res.data)
                  }
                })
              }
            })
            db.collection("comments").doc(item._id).update({
              data: {
                goodNum: res.data[0].goodNum,
                //这个字段的目的是排序时点赞多的排在上面，不然goodNum.length完全够用
                goodnum: _.inc(-1)
              },
              success: (r) => {
                this.setData({
                  [`comment[${index}].likeed`]: false,
                  [`comment[${index}].goodNum`]: res.data[0].goodNum
                })
              }
            })
          }
        })
      } else {
        this.addmessage(item._openid)
        db.collection("commentBack").add({
          //把点赞的一切都录进去了
          data: {
            "underCollection": this.data.undercollection,
            "underid": this.data.underid,
            "underTitle": this.data.underTitle,
            "state": 3,
            "underCommentId": item._id,
            "content": item.content,
            "sendid": this._openid,
            "receiveid": item._openid,
            "sendname": this.data.name,
            "sendimg": this.data.avatarUrl,
            "receivename": item.nickName,
            "receiveimg": item.imgPhoto,
            "time": time
          },
          success: (res) => {
            this.data.comment[index].goodNum.push({
              connectid: res._id,
              openid: this._openid
            })
            console.log(index)
            db.collection("comments").doc(item._id).update({
              data: {
                goodNum: _.push({
                  connectid: res._id,
                  openid: this._openid
                }),
                goodnum: _.inc(1)
              },
              success: (res) => {
                console.log(res)
                this.setData({
                  [`comment[${index}].likeed`]: true,
                  [`comment[${index}].goodNum`]: this.data.comment[index].goodNum
                })

              }
            })
          }
        })
      }
    },
    //提交留言，没什么好说的，还挺简单
    submit() {
      //防止blur后没了值
      let commentValue = this.data.commentValue
      if (this.data.emoji === true) {
        this.setData({
          emoji: false
        })
        this.writeNow({detail:{value:0}})
      }
      this.sensitiveWordsCheck({
        value:commentValue,
        success:(res)=>{
            let time = formatTime(new Date())
            let addComment = {
              "imgPhoto": this.data.avatarUrl,
              "nickName": this.data.name,
              "content": commentValue,
              "goodNum": [],
              "goodnum": 0,
              "underCollection": this.data.undercollection,
              "underid": this.data.underid,
              "underTitle": this.data.underTitle,
              "commentid": [],
              "comment": [],
              "time": time
            }
            db.collection("comments").add({
              data: addComment,
              success: (res) => {
                addComment._id = res._id
                addComment._openid = this._openid
                addComment.likeed = false
                let newArr = [addComment].concat(this.data.comment)
                this.setData({
                  comment: newArr,
                })
                wx.showToast({
                  title: '留言成功',
                  icon: 'success',
                  duration: 1000,
                })

              }
            })
          
        }
      })

    },
    //回复留言主和互相回复相同部分抽出来
    submitBackShare(addComment) {
      db.collection("comments").where({
        _id: this._backid
      }).update({
        data: {
          comment: _.push(addComment)
        },
        success: (res) => {
          this.data.comment[this._index].comment.push(addComment)

          this.setData({
            [`comment[${this._index}].comment`]: this.data.comment[this._index].comment
          })
          wx.showToast({
            title: '回复成功',
            icon: 'success',
            duration: 1000,
          })

        }
      })
    },

    submitBack() {
      const backValue = this.data.backValue
      if (this.data.emoji === true) {
        this.setData({
          emoji: false
        })
        this.hideKeyboard({detail:{value:0}})
      }
      this.sensitiveWordsCheck({
        value:backValue,
        success:(res)=>{
          
            let addComment
            let time = formatTime(new Date())
            this.addmessage(this._backOpenId)
            //如果是回复留言主的话
            if (this._callBackState === 1) {
              db.collection("commentBack").add({
                data: {
                  "underCollection": this.data.undercollection,
                  "underid": this.data.underid,
                  "underTitle": this.data.underTitle,
                  "state": 1,
                  "underCommentId": this._backid,
                  "content": backValue,
                  "sendid": this._openid,
                  "receiveid": this._backOpenId,
                  "sendname": this.data.name,
                  "sendimg": this.data.avatarUrl,
                  "receivename": this.data.commentBackName,
                  "receiveimg": this._backimgPhoto,
                  "time": time
                },
                success: (res) => {
                  addComment = {
                    connectid: res._id,
                    _openid: this._openid,
                    imgPhoto: this.data.avatarUrl,
                    nickName: this.data.name,
                    content: backValue,
                    state: 1,
                    time: time
                  }
                  this.submitBackShare(addComment)
                }
              })
            } else {
              //互相回复的话
              db.collection("commentBack").add({
                data: {
                  "underCollection": this.data.undercollection,
                  "underid": this.data.underid,
                  "underTitle": this.data.underTitle,
                  "state": 2,
                  "underCommentId": this._backid,
                  "content": backValue,
                  "sendid": this._openid,
                  "receiveid": this._backOpenId,
                  "sendname": this.data.name,
                  "sendimg": this.data.avatarUrl,
                  "receivename": this.data.commentBackName,
                  "receiveimg": this._backimgPhoto,
                  "time": time
                },
                success: (res) => {
                  addComment = {
                    connectid: res._id,
                    _openid: this._openid,
                    imgPhoto: this.data.avatarUrl,
                    nickName: this.data.name,
                    content: backValue,
                    acceptName: this.data.commentBackName,
                    state: 2,
                    time: time
                  }
                  this.submitBackShare(addComment)
                }
              })
            }
          
        }
      })
    },
    // 检查是否有违禁词
    sensitiveWordsCheck({value,success}){
      if (this.hasSensitiveWords(value)) {
        wx.showToast({
          title: '含有违禁词!',
          icon: 'error',
          duration: 1000,
        })
      } else {
        // wx.showLoading({
        //   title: '违禁词检查',
        // })
        // wx.cloud.callFunction({
        //   // 需调用的云函数名
        //   name: 'checkComment',
        //   data: {
        //     value: value
        //   },
        //   success: (res) => {
        //     wx.hideLoading({})
        //     if (res.result.result.suggest !== "pass") {
        //       wx.showToast({
        //         title: '含有违禁词!',
        //         icon: 'error',
        //         duration: 1000,
        //       })
        //     } else {
            success()
        //     }
        //   }
        // })
      }
    },

    // 点赞留言回复之前都先确定一下有没有登录，没有就给他登录再放行方法
    comfirmComment(e) {
      const func = e.currentTarget.dataset.func
      if (app.globalData.userInfo !== undefined) {
        console.log(app.globalData)
        this.setData({
          name: app.globalData.userInfo.nickName,
          avatarUrl: app.globalData.userInfo.avatarUrl
        })
        this[func](e)
      } else {
        login().then(() => {
          this.setData({
            name: app.globalData.userInfo.nickName,
            avatarUrl: app.globalData.userInfo.avatarUrl
          })
          this[func](e)
        })
      }
    },
    // 手动对敏感词检测
    hasSensitiveWords(str) {
      const g_reg = /贱|操|杀|贱|傻|疯|炮|奸|猪|笨|屁|麻痹|滚犊子|婊|艹|你妈|尼玛|干|sha|逼|曹尼玛|干|fuck|shit|damn|鸡鸡|草/gm
      if (str == '' || str == 'undefined') return false;
      if (g_reg.test(str)) { // 如果检测有违规,就返回true
        return true;
      }
    },
  }
})